﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class CloudBehavior : MonoBehaviour 
{
    public float _maxRessource = 100f;
    public float _gainRessourcePerSec = 0.2f;
    public float _loseRessourcePerSec = 1f;
    public int _hpPerSec = 1;

    public int _percentageOfMaxAtStart = 25;
    public bool _ressouceIncreasing = true;

    [HideInInspector]
    public List<BehaviorUnits> _listUnit = new List<BehaviorUnits>();

    private float _actualRessource = 0f;
    private ParticleSystem _particleSystem;
  

	// Use this for initialization
	void Start () 
    {
        _particleSystem = this.GetComponent<ParticleSystem>();

        _actualRessource = _maxRessource * (float)_percentageOfMaxAtStart / 100f;
        StartCoroutine(SpecificUpdate());
        StartCoroutine(GainRessource());
        StartCoroutine(LoseRessource());
	}
	
	// Update is called once per frame
	void Update () 
    {
	
	}


    public int TakeRessource (int nbToTake)
    {
        while (_actualRessource - nbToTake < 0)
        {
            nbToTake--;
        }
        _actualRessource -= nbToTake;
        return nbToTake;
    }

    void CheckRain()
    {
        if (_actualRessource >= _maxRessource)
        {
            _ressouceIncreasing = false;
        }
        else if (_actualRessource <= 0f)
        {
            _ressouceIncreasing = true;
        }
    }

    IEnumerator SpecificUpdate()
    {
        while(true)
        {
            CheckRain();
            yield return new WaitForSeconds(0.1f);
        }
        
    }

    IEnumerator LoseRessource()
    {
        while (true)
        {
            if (!_ressouceIncreasing)
            {
                if (_particleSystem.enableEmission == false)
                {
                    _particleSystem.enableEmission = true;
                }
                _actualRessource -= _loseRessourcePerSec;

                foreach (BehaviorUnits unit in _listUnit)
                {
                    unit.GainLife(_hpPerSec);
                }
            }
            yield return new WaitForSeconds(1f);
        }
    }

    IEnumerator GainRessource()
    {
        while (true)
        {
            if (_ressouceIncreasing)
            {
                if (_particleSystem.enableEmission == true)
                {
                    _particleSystem.enableEmission = false;
                }
                _actualRessource += _gainRessourcePerSec;
            }
            yield return new WaitForSeconds(1f);
        }
    }
}
